package gui;

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.Observable;
import java.util.Observer;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

import logic.UdpCommPackage;





public class UserFrame implements ActionListener, Observer{
	
	private UdpCommPackage udpComms;
	private JTextArea textArea; 
	private 
	UserFrame(){
		JFrame frame = new JFrame("Let's Play Marco Polo!");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		int width = 1280;
		int height = 1024;
		
		frame.setSize(width, height);
		
		//create textArea and add to frame
		
		textArea = new JTextArea();
		textArea.setEditable(false);
		
		frame.add(new JScrollPane(textArea), BorderLayout.CENTER);
		frame.setVisible(true);

		try {
			udpComms = new UdpCommPackage();
			udpComms.addObserver(this);
			
			//Create JPanel of menu options
			JPanel menuPanel = new JPanel();
			menuPanel.setLayout(new GridLayout(1, 3));
			
			//create buttons
			JButton marco = new JButton("Say Marco!");
			marco.addActionListener(this);
			menuPanel.add(marco);
			
			JButton clear = new JButton("Clear Screen");
			clear.addActionListener(this);
			menuPanel.add(clear);
			
			JButton printAddresses = new JButton("Who's Playing?");
			printAddresses.addActionListener(this);
			menuPanel.add(printAddresses);
			
			//add menuPanel to frame
			frame.add(menuPanel, BorderLayout.SOUTH);
			
			frame.validate();
			
		} catch (IOException e) {
			textArea.setText("UDP Comms IO Exception\n");
			e.printStackTrace();
		}
		
	}
	public static void main(String[] args) {
		new UserFrame();
	}
	@Override
	public void actionPerformed(ActionEvent e) {
		String command = e.getActionCommand();
		if(command.equals("Say Marco!")){
			//broadcasts a ping message
			try {
				udpComms.sendPing();
				String text = textArea.getText();
				text +="\nYou say: Marco!";
				textArea.setText(text);
				
			} catch (IOException e1) {
				textArea.setText("UDP Comms IO Exception");
			}
		}
		else if (command.equals("Clear Screen")){
			//clears the screen
			textArea.setText("");
		}
		else if (command.equals("Who's Playing?")){
			//lists IPs in address list
			String text = textArea.getText();
			text +="\nPlayers:";
			String [] players = udpComms.getAddressList();
			for(String player : players){
				text +="\n"+player;
			}
			textArea.setText(text);
		}
		
	}
	@Override
	public void update(Observable arg0, Object arg1) {
		//add the text of the 
		textArea.setText(textArea.getText()+"\n"+arg1.toString());
	}

}
